<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  genModelClassifyAddApi,
  genModelClassifyEditApi,
  genModelClassifyQueryByIdApi,
} from '#/api/gen/modelType';
import { asyncValidDataApi } from '#/utils/handle/async-rules';

const record = ref({});
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
  commonConfig: {
    boolean: true,
    labelWidth: 60,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入名称',
      },
      fieldName: 'name',
      label: '名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入编码',
      },
      dependencies: {
        triggerFields: ['code'],
        // 实现异步API校验
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z.string({ required_error: '请输入数据源编码' }),
            {
              tableName: 'online_model_classify',
              fieldName: 'code',
              rowId,
              sqlSelect: `del_flag = 0`,
            },
          );
        },
      },
      fieldName: 'code',
      label: '编码',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      defaultValue: 10,
      componentProps: {
        placeholder: '请输入排序',
      },
      fieldName: 'sortRank',
      label: '排序',
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});
const [Modal, modalApi] = useVbenModal({
  title: '分类',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}分类`,
      });
      if (record.value.id) {
        initFun();
      }
    }
  },
});
async function initFun() {
  const res = await genModelClassifyQueryByIdApi({ id: record.value.id });
  await formApi.setValues(res, false);
}

async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await genModelClassifyEditApi(values);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await genModelClassifyAddApi(values);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
